package com.mec.web.y2012.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class ValidationServlet
 */
@WebServlet("/ajax/validationServlet")
public class ValidationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ValidationServlet() {
        super();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		
		//
		boolean passed = validateDate(request.getParameter("birthDate"));
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		String message = "You have entered an invalid date.";
	
		if(passed){
			message = "You have entered a vaild date.";
		}
		
		out.println("<response>");
		out.println("<passed>" + passed + "</passed>");
		out.println("<message>" +message +"</message>");
		out.println("</response>");
		out.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	
	private boolean validateDate(String date){
		boolean isValid = false;
		
		if(null != date){
			SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
			try{
				formatter.parse(date);
				isValid = true;
			}catch(ParseException pe){
				logger.debug(pe);
			}
		}
		
		return isValid;
	}
	
	private static final Logger logger = 
			Logger.getLogger(ValidationServlet.class);

}
